package com.lagou.session;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author srh
 * @date 2020/02/22
 **/
public class SimpleExecutor implements Executor {

    private Connection connection;

    @Override
    public int executor(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        connection = configuration.getDataSource().getConnection();
        BoundSql boundSql = getBoundSql(mapperStatement.getSql());
        String sql = boundSql.getSqlTxt();
        connection.setAutoCommit(false);
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        Class<?> parameterClass = mapperStatement.getParameterType();
        List<String> sqlParams = boundSql.getParameterMappings().stream().map(ParameterMapping::getContent).collect(Collectors.toList());
        for (int i = 0; i < sqlParams.size(); i++) {
            String name = sqlParams.get(i);
            Field declaredField = parameterClass.getDeclaredField(name);
            declaredField.setAccessible(true);
            // 参数的值
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement.executeUpdate();
    }

    @Override
    public <T> List<T> query(Configuration configuration, MapperStatement mapperStatement, Object... params)
            throws SQLException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException, NoSuchFieldException {

        // 获取连接
        connection = configuration.getDataSource().getConnection();
        // connection = DriverManager.getConnection("jdbc:mysql:///local_daily?characterEncoding=utf-8", "root", "123456789");
        // 解析sql
        BoundSql boundSql = getBoundSql(mapperStatement.getSql());
        String sql = boundSql.getSqlTxt();
        Class<?> parameterClass = mapperStatement.getParameterType();
        // #{} 数组
        List<String> sqlParams = boundSql.getParameterMappings().stream().map(ParameterMapping::getContent).collect(Collectors.toList());

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < sqlParams.size(); i++) {
            String name = sqlParams.get(i);
            Field declaredField = parameterClass.getDeclaredField(name);
            declaredField.setAccessible(true);
            // 参数的值
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 通过内省封装返回实体
        List<T> results = new ArrayList<>();
        Class<?> resultType = mapperStatement.getResultType();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            T instance = (T) resultType.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                // 创建属性描述器
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance, value);
            }
            results.add(instance);
        }
        return results;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterMappings);
    }

    @Override
    public void close() throws SQLException {
        if (null != connection) {
            connection.close();
        }
    }

    @Override
    public void commit() throws SQLException {
        if (null != connection) {
            connection.commit();
        }
    }
}
